import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => {
    const userId = localStorage.getItem('userId')
    const username = localStorage.getItem('username')
    const token = localStorage.getItem('token')
    
    console.log('初始化用户状态:', { userId, username, token }) // 调试信息
    
    return {
      userId: userId || '',
      username: username || '',
      token: token || ''
    }
  },

  actions: {
    setUserInfo(userInfo) {
      console.log('设置用户信息:', userInfo) // 调试信息
      
      if (!userInfo || !userInfo.id) {
        console.error('无效的用户信息')
        return
      }

      this.userId = userInfo.id
      this.username = userInfo.username
      this.token = userInfo.token
      
      // 保存到本地存储
      localStorage.setItem('userId', userInfo.id)
      localStorage.setItem('username', userInfo.username)
      localStorage.setItem('token', userInfo.token)
      
      console.log('用户信息已保存:', {
        userId: this.userId,
        username: this.username,
        hasToken: !!this.token
      }) // 调试信息
    },

    clearUserInfo() {
      console.log('清除用户信息') // 调试信息
      
      this.userId = ''
      this.username = ''
      this.token = ''
      
      // 清除本地存储
      localStorage.removeItem('userId')
      localStorage.removeItem('username')
      localStorage.removeItem('token')
    }
  }
}) 